/*
 * JsonUtil.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the org.geek.util, Version 1.0 (the "License");
 *
 */
package org.geek.common.util;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.geek.common.base.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p></p>
 * @author ninglong bhd2973@qq.com
 * @version V1.0
 */
public class JsonUtil {
	
	private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
	
	private static ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * <p>将对象转成json字符串<p>
	 * @param value
	 * @return
	 */
	public static String toJson(Object value){
		try {
			return mapper.writeValueAsString(value);
		} catch (Exception e) {
			if(logger.isDebugEnabled()){
				e.printStackTrace();
				logger.debug("json error");
			}
			throw new BaseException();
		} 
	}
	
	/**
	 * <p>将json字符转成相应的对象<p>
	 * @param json
	 * @param targetCls
	 * @return
	 */
	public static <T> T toJavaBean(String json,Class<T> targetCls){
		try {
			return mapper.readValue(json, targetCls);
		} catch (Exception e) {
			if(logger.isDebugEnabled()){
				e.printStackTrace();
				logger.debug("json error");
			}
			throw new BaseException();
		} 
	}
	/**
	 * <p>将json字符转成相应的对象<p>
	 * @param json
	 * @param targetCls
	 * @return
	 */
	public static <T> T toJavaBean(JsonNode json,Class<T> targetCls){
		try {
			return mapper.readValue(json, targetCls);
		} catch (Exception e) {
			if(logger.isDebugEnabled()){
				e.printStackTrace();
				logger.debug("json error");
			}
			throw new BaseException();
		} 
	}
	
	/**
	 * <p>从json字符里取出jsonNode对象<p>
	 * @param json
	 * @return
	 */
	public static JsonNode getJsonNode(String json){
		try {
			return mapper.readTree(json);
		} catch (Exception e) {
			if(logger.isDebugEnabled()){
				e.printStackTrace();
				logger.debug("json error");
			}
			throw new BaseException();
		}
	}
}
